package com.hyh.springcloud.controller;

import com.hyh.springcloud.entity.Payment;
import com.hyh.springcloud.result.AjaxResult;
import com.hyh.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Summerday
 */

@Slf4j
@RestController
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping("/payment")
    public AjaxResult create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        log.info("插入结果 : " + result);
        return result > 0 ? AjaxResult.ok() : AjaxResult.error();
    }


    @GetMapping("/payment/{id}")
    public AjaxResult getById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        log.info("端口 : {} , 获得结果 : {}", serverPort, payment);
        return payment == null ? AjaxResult.error() : AjaxResult.ok(serverPort, payment);
    }

    @GetMapping("/payment/discovery")
    public Object discovery() {
        Map<String, Object> map = new HashMap<>();
        List<String> services = discoveryClient.getServices();
        services.forEach(log::info);
        map.put("获取的服务列表", services);
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        List<String> instanceList = new ArrayList<>();
        instances.forEach(x -> {
            log.info(x.getServiceId() + "\n" + x.getHost() + "\n" + x.getPort() + "\n" + x.getUri());
            instanceList.add("ServiceId : " + x.getServiceId() + " Host : " + x.getHost() + " Port : " + x.getPort() + " uri : " + x.getUri());
        });
        map.put("服务cloud-payment-service上的实例", instanceList);
        return map;
    }

    @GetMapping("/payment/lb")
    public String getServerPortLb() {
        return serverPort;
    }

    @GetMapping("/payment/timeOut")
    public String paymentTimeOut() {

        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }

    @GetMapping("/payment/zipkin")
    public String paymentZipkin(){
        return "payment zipkin !";
    }
}
